#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SLInit(SL* ps)
{
	ps->data = (SeqDataType*)malloc(sizeof(SeqDataType)*DEF_CAPACITY);
	if (ps->data == NULL)
	{
		perror("malloc fail\n");
		return;
	}

	ps->capacity = DEF_CAPACITY;
	ps->size = 0;
}

void CheckSLcapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SeqDataType* ptr = (SeqDataType*)realloc(ps->data, sizeof(SeqDataType) * (ps->capacity * 2));
		if (ptr == NULL)
		{
			perror("realloc fail\n");
			return;
		}

		ps->data = ptr;
		ptr = NULL;
		ps->capacity *= 2;
	}
}

void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

void SLDestory(SL* ps)
{
	free(ps->data);
	ps->data = NULL;
	ps->size = ps->capacity = 0;
}


void SeqPushBack(SL* ps, SeqDataType x)
{
	//assert(ps);
	//CheckSLcapacity(ps);
	//ps->data[ps->size] = x;
	//ps->size++;
	SLInsert(ps, ps->size ,x);
}


void SeqPopBack(SL* ps)
{
	//assert(ps->size >= 0 && ps);
	//ps->size--;

	SLErase(ps,ps->size-1);
}

void SeqPushFront(SL* ps, SeqDataType x)
{
	//assert(ps);
	//CheckSLcapacity(ps);
	//int end = ps->size;
	//while (end > 0)
	//{
	//	ps->data[end] = ps->data[end - 1];
	//	end--;
	//}
	//ps->data[0] = x;
	//ps->size++;
	SLInsert(ps, 0,x);
}

void SeqPopFront(SL* ps)
{
	//assert(ps);
	//assert(ps->size > 0);

	//int begin = 1;
	//while (begin < ps->size)
	//{
	//	ps->data[begin - 1] = ps->data[begin];
	//	begin++;
	//}
	//ps->size--;
	SLErase(ps,0);
}

void SLInsert(SL* ps, int pos, SeqDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size );
	CheckSLcapacity(ps);
	int end = ps->size;
	while (end > pos)
	{
		ps->data[end] = ps->data[end - 1];
		end--;
	}

	ps->data[pos] = x;
	ps->size++;
}

int SLFind(SL* ps, SeqDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
			return i;
	}
	return -1;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->data[begin - 1] = ps->data[begin];
		++begin;
	}

	ps->size--;
}